package com.sk.bilibili.typeHandler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 邵康
 * @date 2021/11/24 19:41
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {

    @Override
    public void setParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i,String.join(",",parameter));
    }

    @Override
    public String[] getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return getRes(value);
    }

    private String[] getRes(String value) {
        if(value.equals(""))return new String[0];
        return value.split(",");
    }

    @Override
    public String[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return getRes(value);
    }

    @Override
    public String[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return new String[0];
    }

}
